//
//  JSONSerializationExtension.swift
//  YYProject
//
//  Created by 陆文宇 on 2017/9/4.
//  Copyright © 2017年 陆文宇. All rights reserved.
//

import Foundation

extension JSONSerialization {
    
    open class func yy_string(withJSONObject obj: Any, options opt: JSONSerialization.WritingOptions = []) throws -> String {
        do {
            let data = try JSONSerialization.data(withJSONObject: obj, options: opt)
            if let string = String(data: data, encoding: .utf8) {
                return string
            } else {
                throw NSError(domain: "Data 无法转换成 String", code: 0, userInfo: nil)
            }
        } catch let error {
            throw error
        }
    }
    
    open class func yy_jsonObject(with string: String, options opt: JSONSerialization.ReadingOptions = []) throws -> Any {
        if let data = string.data(using: .utf8) {
            do {
                return try JSONSerialization.jsonObject(with: data, options: opt)
            } catch let error {
                throw error
            }
        } else {
            throw NSError(domain: "String 无法转换成 Data", code: 0, userInfo: nil)
        }
    }
    
}
